<?php


namespace app\webactive\service;

/**
 * 抽奖服务类
 * Class Prize
 * @package app\webactiv\service
 */
class Prize
{
    /**
     * 中奖概率
     * @var array
     */
    protected $prizeProbability = [];

    /**
     * 奖品详情
     */
    protected $prizeInfo = [];

    /**
     * 抽奖范围精度 范围越大精度越高
     * @var int[]
     */
    protected $prizeInitScope = [1, 100000000];

    /**
     * 设置中奖概率
     * @param array $prizeProbability
     * @return $this
     */
    public function setPrizeProbability(array $prizeProbability)
    {
        $this->prizeProbability = $prizeProbability;

        return $this;
    }

    /**
     * 设置奖品信息
     * @param array $prizeInfo
     * @return $this
     */
    public function setPrizeInfo(array $prizeInfo)
    {
        $this->prizeInfo = $prizeInfo;

        return $this;
    }

    /**
     * 设置抽奖精度
     * @param array $prizeInitScope
     * @return $this
     */
    public function setPrizeInitScope(array $prizeInitScope)
    {
        $this->prizeInitScope = $prizeInitScope;

        return $this;
    }

    /**
     * 抽奖
     */
    public function getPrizeId()
    {
        // 抽奖
        $num = mt_rand(...$this->prizeInitScope);
        // 基准概率
        $resetBaseProbability = 1 / array_sum($this->prizeProbability);
        // 计算抽奖所中奖项
        $startProbability = 0;
        $resPrizeId = 0;
        foreach ($this->prizeProbability as $prizeId => $value)
        {
            if ($num <= ($value * $resetBaseProbability + $startProbability) * $this->prizeInitScope[1])
            {
                $resPrizeId = $prizeId;
                break;
            }

            $startProbability += $value * $resetBaseProbability;
        }

        return $resPrizeId;
    }
}
